import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Feed } from './feed.entity';

@Injectable()
export class FeedsService {
  private readonly logger = new Logger(FeedsService.name);

  constructor(
    @InjectRepository(Feed)
    private feedRepository: Repository<Feed>,
  ) {}

  // 创建动态
  async createFeed(userId: number, feedData: Partial<Feed>): Promise<Feed> {
    this.logger.log(`用户 ${userId} 发布动态`);
    const feed = this.feedRepository.create({
      userId,
      ...feedData,
    });
    return await this.feedRepository.save(feed);
  }

  // 获取动态列表
  async getFeeds(page: number = 1, limit: number = 10): Promise<Feed[]> {
    this.logger.log(`获取动态列表，页码: ${page}, 每页数量: ${limit}`);
    return await this.feedRepository
      .createQueryBuilder('feed')
      .leftJoinAndSelect('feed.user', 'user')
      .orderBy('feed.createdAt', 'DESC')
      .skip((page - 1) * limit)
      .take(limit)
      .getMany();
  }

  // 根据用户ID获取动态
  async getFeedsByUserId(userId: number): Promise<Feed[]> {
    this.logger.log(`获取用户 ${userId} 的动态`);
    return await this.feedRepository
      .createQueryBuilder('feed')
      .where('feed.userId = :userId', { userId })
      .orderBy('feed.createdAt', 'DESC')
      .getMany();
  }

  // 根据ID获取动态
  async getFeedById(id: number): Promise<Feed | null> {
    this.logger.log(`获取动态，ID: ${id}`);
    return await this.feedRepository
      .createQueryBuilder('feed')
      .leftJoinAndSelect('feed.user', 'user')
      .where('feed.id = :id', { id })
      .getOne();
  }

  // 删除动态
  async deleteFeed(id: number, userId: number): Promise<boolean> {
    this.logger.log(`删除动态，ID: ${id}, 用户ID: ${userId}`);
    const result = await this.feedRepository.delete({ id, userId });
    return (result.affected ?? 0) > 0;
  }
}
